let express = require('express');
let router = express.Router();

const courseService = require('../service/courseService');

// 引入jwt验证方法的中间件
const checkJWTMiddleWare = require('../middleWare/checkJWTMiddleWare');
router.use(checkJWTMiddleWare);

/*
 * 懒加载获取课程接口
 */
router.post('/getCourse', async function(req, res, next) {
    let uid = req.jwtResult.data.uid;
    let { lastId } = req.body;
    let result = await courseService.getCourse(uid, lastId);
    res.status(result.success ? 200 : 400).json(result);
});

/*
 * 查看课程详情接口
 */
router.post('/getCourseInfo', async function(req, res, next) {
    let uid = req.jwtResult.data.uid;
    let { courseId } = req.body;
    let result = await courseService.getCourseInfo(uid, courseId);
    res.status(result.success ? 200 : 400).json(result);
});

/*
 * 购买课程接口
 */
router.post('/buyCourse', async function(req, res, next) {
    let uid = req.jwtResult.data.uid;
    let { courseId } = req.body;
    let result = await courseService.buyCourse(uid, courseId);
    res.status(result.success ? 200 : 400).json(result);
});

/*
 * 课程购买记录接口
 */
router.get('/getJoinCourse', async function(req, res, next) {
    let uid = req.jwtResult.data.uid;
    let result = await courseService.getJoinCourse(uid);
    res.status(result.success ? 200 : 400).json(result);
});

/*
 * 分页获取所有课程的接口
 */
router.get('/getAllCourse', async function(req, res, next) {
    let uid = req.jwtResult.data.uid;
    let page = parseInt(req.query.page || 1);
    let result = await courseService.getAllCourse(uid, page);
    res.status(result.success ? 200 : 400).json(result);
});

/*
 * 发布课程接口
 */
router.post('/publishCourse', async function(req, res, next) {
    let uid = req.jwtResult.data.uid;
    let { name, price, description, imageUrl } = req.body;
    let result = await courseService.publishCourse(uid, name, price, description, imageUrl);
    res.status(result.success ? 200 : 400).json(result);
});

// 删除课程
router.post('/deleteCourse', async function(req, res, next) {
    let uid = req.jwtResult.data.uid;
    let { courseId } = req.body;
    let result = await courseService.deleteCourse(uid, courseId);
    res.status(result.success ? 200 : 400).json(result);
});

module.exports = router;